package cn.yangliu.redis.impl;

import cn.yangliu.redis.RedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Xiong Hao
 */
@Component
public class RedisServiceImpl implements RedisService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String get(String key) {
        return opsForValue().get(key);
    }

    @Override
    public void set(String key, String value) {
        opsForValue().set(key, value);
    }

    @Override
    public void set(String key, String value, long liveTime) {
        opsForValue().set(key, value, liveTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void del(String... keys) {
        stringRedisTemplate.delete(Arrays.asList(keys));
    }

    @Override
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public Set<String> keys(String pattern) {
        return stringRedisTemplate.keys(pattern);
    }

    private ValueOperations<String, String> opsForValue() {
        return stringRedisTemplate.opsForValue();
    }
}
